<!--
  @Description:选择商品
  @Author:zqy
  @Date:2022-12-08 20:07:54
  @Last Modified by:zqy
  @Last Modified time:2022-12-08 20:07:54
-->
<template>
  <el-dialog
    ref="refDlg"
    v-el-drag-dialog
    :width="checkable?'90%':'700px'"
    :title="!!(detail && detail.id)?'替换商品:'+detail.skuName:'商品选择'"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @close="closeDialog"
  >
    <div class="table-main">
      <div class="table-flex">
        <table-box
          ref="refAllTable"
          :table-config="tableConfig"
          :other-filters="otherFilters"
          :table-height="400"
          table-default-expand-all
          :table-row-key="tableRowKey"
          :table-row-class-name="tableRowClassName"
          :table-tree-props="{children: 'skus', hasChildren: 'hasChildren'}"
          :selected-arry.sync="tableSelected"
          :show-custom-setting="false"
          :show-custom-combine="false"
          :table-sortable="false"

          @data-change="getProductTableData"
          @selection-change="handleSelectionChange"
        >
          <!--  reserve-selection
          show-selection -->
          <el-table-column
            v-if="checkable"
            slot="before"
            type="selection"
            :selectable="tableSelectable"
            reserve-selection
            width="40"
          />
        </table-box>
      </div>
      <div v-if="checkable" class="table-flex">
        <div class="qup-title-box mg10"><span class="border" /><span>已选商品{{ selectedProductData.length?`(${selectedProductData.length})`:'' }}</span></div>
        <div class="table-list-box">
          <el-table
            style="width: 100%"
            :data="selectedProductData"
            :height="400"
            header-row-class-name="table-list-header"
            highlight-current-row
            border
          >
            <el-table-column type="index" label="序号" width="50" fixed="left" />
            <el-table-column prop="skuName" label="商品名称" min-width="150" />
            <el-table-column prop="skuCode" label="商品编码" width="150" />
            <el-table-column label="操作" width="70" fixed="right" align="center">
              <template v-slot="{row}">
                <el-button class="my-button no-pd" type="text" size="mini" @click="handleDeleteSelected(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="closeDialog">取 消</el-button>
      <el-button v-loading="submiting" type="primary" size="mini" @click="handleSure">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { saveFloorDetail, saveBatchFloorDetail } from '@/api/floorProductDetail'
export default {
  name: 'CheckProductItem',
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    detail: {
      type: [String, Object],
      default: ''
    },
    floorId: {
      type: String,
      default: ''
    }
  },
  data() {
    const that = this
    return {
      otherFilters: [],
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/gcenter/page`,
        onlySearchBar: true,
        tabIndex: 997,
        setting: [
          {
            prop: 'picUrl',
            label: '商品图片',
            width: 100,
            overflowHidden: false,
            sortable: false,
            type: 'hidden',
            align: 'center',
            render: (_h, row) => {
              const iconUrl = row.picUrl || ''
              if (iconUrl) {
                const url = that.formatImageUrl(iconUrl)
                return (<div class='cover-image'><img src={url} /></div>)
              }
              return ''
            }
          },
          {
            prop: 'name',
            label: '商品名称',
            minWidth: 200,
            formatData: ({ name, skuName }) => {
              return skuName || name
            }
          },
          {
            prop: 'code',
            label: '商品编码',
            minWidth: 150,
            formatData: ({ code, skuCode }) => {
              return skuCode || code
            }
          }
        ]
      },
      tableSelected: [], // 单选行
      selectedProductData: [], // 当前已选所有商品
      cancelSelectedProducts: [], // 临时存储非当前页的移除数据
      currentTableData: [], // 当前页表格数据
      allProductData: {}, // 当前所查询的所有数据
      submiting: false
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    checkable() {
      return !(this.detail && this.detail.id)
    }
  },
  watch: {
    allProductData: {
      handler(val, oldVal) {
        this.$nextTick(() => {
          this.reSetTableSelection()
        })
      },
      deep: true
    }
  },
  methods: {
    closeDialog() {
      this.dialogShow = false
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      if (this.checkable) {
        const filterArr = this.selectedProductData.filter(item => item.skuCode === row.skuCode)
        return filterArr.length > 0 ? 'selected-highlight' : 'white-row'
      } else {
        return ''
      }
    },
    tableRowKey(row) {
      return row.rowId || `${row.keyIndex}_${row.id}`
    },
    // 复选框是否可选(组合商品可选，非组合商品可选)
    tableSelectable(row) {
      return !!row.skuCode
    },
    // 获取搜索产品表格数据变化
    getProductTableData(res) {
      if (res && res.data && res.data.records) {
        const { page } = res.data
        const skuList = []
        res.data.records.forEach(row => {
          const spuId = row.id
          if (row.skus && row.skus.length > 0) {
            row.skus.forEach(v => {
              this.$set(v, 'spuId', spuId)
              this.$set(v, 'rowId', `${spuId}_${v.id}`)
              skuList.push(v)
            })
          }
          this.$set(row, 'rowId', spuId)
        })
        this.currentTableData = skuList
        const selectKey = `${page}`
        if (this.allProductData[selectKey]) {
          this.allProductData[selectKey] = []
        }
        this.$set(this.allProductData, selectKey, skuList)
      }
    },
    // 重置当前页已选中产品的复选状态
    reSetTableSelection() {
      const cancelList = this.cancelSelectedProducts.filter(item => {
        const tmp = this.currentTableData.find(v => v.skuCode === item.skuCode)
        if (tmp && tmp.skuCode) { // 在当前页表格数据中则取消选中
          this.$refs.refAllTable.toggleRowSelection(tmp, false)
        }
        return tmp.length === 0 // 返回非当前页数据
      })
      this.cancelSelectedProducts = cancelList

      const initCheckedRows = []
      this.currentTableData.forEach(item => {
        const index = this.selectedProductData.findIndex(v => v.skuCode === item.skuCode)
        const tmp = this.selectedProductData[index] || null
        if (tmp && tmp.skuCode) {
          // 在当前页表格数据中数据选中
          this.selectedProductData.splice(index, 1)
          this.$refs.refAllTable.toggleRowSelection(tmp, false)
          initCheckedRows.push(item)
        }
      })
      initCheckedRows.forEach(item => {
        this.$refs.refAllTable.toggleRowSelection(item, true)
      })
    },
    // 产品复选框操作
    handleSelectionChange(rows) {
      const { selectedProductData = [] } = this
      // 过滤掉非当前页已删除的产品
      const enbleSelectRows = rows.filter(row => {
        const index = this.cancelSelectedProducts.findIndex(v => v.skuCode === row.skuCode)
        return index === -1
      })

      this.selectedProductData = enbleSelectRows.map(row => {
        // 检测当前复选行是否已选中
        const repeatPros = selectedProductData.filter(v => v.skuCode === row.skuCode)
        if (repeatPros && repeatPros.length) {
          return repeatPros[0] // 已选中
        } else {
          return row // 新添加
        }
      })
    },
    // 移除已选择产品
    handleDeleteSelected(row) {
      const tmp = this.currentTableData.filter(item => row.skuCode === item.skuCode)
      if (tmp.length > 0) { // 在当前页表格数据中则取消选中
        this.$refs.refAllTable.toggleRowSelection(tmp[0], false)
        const index = this.selectedProductData.findIndex(v => v.skuCode === tmp[0].skuCode)
        if (index > -1) {
          this.selectedProductData.splice(index, 1)
        }
      } else { // 未在当前表格数据中，则加入到取消选中的数据集中，并从已选产品表中删除
        let tmpArr = []
        for (const key in this.allProductData) {
          tmpArr = tmpArr.concat(this.allProductData[key])
        }
        const repeatRows = tmpArr.filter(item => row.skuCode === item.skuCode)
        if (repeatRows && repeatRows.length) {
          this.$refs.refAllTable.toggleRowSelection(repeatRows[0], false)
        }
        this.cancelSelectedProducts.push(row)
        const index = this.selectedProductData.findIndex(v => v.skuCode === row.skuCode)
        if (index > -1) {
          this.selectedProductData.splice(index, 1)
        }
      }
    },
    handleSure() {
      if (this.submiting) return
      let data = {}
      if (this.checkable) {
        // 新增
        if (this.selectedProductData.length === 0) {
          this.$message.warning('请选择商品')
          return
        }
        const flag = this.selectedProductData.every(v => {
          return ![null, undefined, ''].includes(v.skuCode)
        })
        if (!flag) {
          this.$message.warning('只能选择SKU')
          return
        }
        data = this.selectedProductData.map(v => {
          return {
            floorConfId: this.floorId,
            skuCode: v.skuCode,
            skuName: v.skuName,
            spuId: v.spuId,
            skuId: v.id
          }
        })
      } else {
        // 替换
        if (this.tableSelected.length === 0) {
          this.$message.warning('请选择替换商品')
          return
        }
        const { skuCode, skuName, id, spuId } = this.tableSelected[0]
        if ([null, undefined, ''].includes(skuCode)) {
          this.$message.warning('只能选择SKU')
          return
        }
        data = {
          id: this.detail.id,
          floorConfId: this.floorId,
          skuCode,
          skuName,
          spuId,
          skuId: id
        }
      }
      this.submiting = true
      const saveFunc = this.checkable ? saveBatchFloorDetail : saveFloorDetail
      saveFunc(data).then(res => {
        this.submiting = false
        if (res.success === 1) {
          this.$message.success(`操作成功`)
          this.$emit('success', !!data.id)
          this.closeDialog()
        }
      }).catch(() => {
        this.submiting = false
      })
    }
  }
}
</script>

<style lang='scss' scoped>
 .cover-image{
    padding: 5px 0;
    line-height: 0;
    font-size: 0;
    img{
      height: 40px;
      width: 40px;
      object-fit: contain;
    }
  }

  /deep/ .el-table [class*=el-table__row--level] .el-table__expand-icon{
    float:left;
    margin-top: 10px;
  }
  /deep/ .white-row{
    background: #fff !important;
  }
  /deep/ .el-checkbox .is-disabled{
    visibility: hidden;
  }
  .table-main{
    display: flex;
    .table-flex{
      &:first-child{
        flex: 1;
      }
      &:last-child{
        width:50%;
        padding-left: 10px;
      }
    }
  }
  .mg10{
    line-height: 32px;
    margin-bottom: 10px;
  }
  .no-pd{
    padding: 0 !important;
  }
</style>
